#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
路径管理模块
处理不同部署环境下的路径问题，确保资源文件能正确找到
"""

import os
import sys
from pathlib import Path
from typing import Union

class PathManager:
    """路径管理器"""
    
    def __init__(self):
        self._app_dir = None
        self._data_dir = None
        self._config_dir = None
        self._logs_dir = None
        self._deployment_mode = self._detect_deployment_mode()
        self._init_paths()
    
    def _detect_deployment_mode(self) -> str:
        """检测部署模式"""
        if getattr(sys, 'frozen', False):
            # PyInstaller打包后的exe
            return "exe"
        elif hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
            # 虚拟环境
            return "venv"
        else:
            # 普通Python环境
            return "python"
    
    def _init_paths(self):
        """初始化路径"""
        if self._deployment_mode == "exe":
            # PyInstaller打包后的exe模式
            # 始终使用exe文件所在目录作为应用目录
            # sys._MEIPASS是临时解压目录，不适合存放数据和配置
            self._app_dir = Path(sys.executable).parent
        else:
            # 开发环境或虚拟环境
            # 找到项目根目录（包含main_new.py的目录）
            current_file = Path(__file__)
            self._app_dir = current_file.parent.parent.parent
            
            # 确保找到正确的项目根目录
            if not (self._app_dir / "main_new.py").exists():
                # 如果没找到main_new.py，尝试当前工作目录
                if (Path.cwd() / "main_new.py").exists():
                    self._app_dir = Path.cwd()
                else:
                    # 最后尝试脚本所在目录的上级目录
                    self._app_dir = current_file.parent.parent.parent
        
        # 设置数据目录（总是相对于应用目录）
        self._data_dir = self._app_dir / "data"
        self._config_dir = self._app_dir
        self._logs_dir = self._app_dir / "logs"
        
        # 确保目录存在
        self._data_dir.mkdir(exist_ok=True)
        self._logs_dir.mkdir(exist_ok=True)
    
    @property
    def deployment_mode(self) -> str:
        """部署模式"""
        return self._deployment_mode
    
    @property
    def app_dir(self) -> Path:
        """应用程序目录"""
        return self._app_dir
    
    @property
    def data_dir(self) -> Path:
        """数据目录"""
        return self._data_dir
    
    @property
    def config_dir(self) -> Path:
        """配置目录"""
        return self._config_dir
    
    @property
    def logs_dir(self) -> Path:
        """日志目录"""
        return self._logs_dir
    
    def get_config_file(self, filename: str = "config.json") -> Path:
        """获取配置文件路径"""
        return self._config_dir / filename
    
    def get_database_file(self, filename: str = "wmssimple.db") -> Path:
        """获取数据库文件路径"""
        return self._data_dir / filename
    
    def get_log_file(self, filename: str) -> Path:
        """获取日志文件路径"""
        return self._logs_dir / filename
    
    def get_resource_path(self, relative_path: Union[str, Path]) -> Path:
        """获取资源文件路径"""
        return self._app_dir / relative_path
    
    def ensure_dir_exists(self, path: Union[str, Path]) -> Path:
        """确保目录存在"""
        path = Path(path)
        path.mkdir(parents=True, exist_ok=True)
        return path
    
    def get_absolute_path(self, relative_path: Union[str, Path]) -> str:
        """获取绝对路径字符串"""
        return str(self._app_dir / relative_path)
    
    def debug_info(self) -> dict:
        """获取调试信息"""
        return {
            "deployment_mode": self._deployment_mode,
            "app_dir": str(self._app_dir),
            "data_dir": str(self._data_dir),
            "config_dir": str(self._config_dir),
            "logs_dir": str(self._logs_dir),
            "sys.executable": sys.executable,
            "sys.frozen": getattr(sys, 'frozen', False),
            "sys._MEIPASS": getattr(sys, '_MEIPASS', None),
            "cwd": str(Path.cwd()),
            "__file__": __file__
        }

# 全局路径管理器实例
path_manager = PathManager() 